package org.wyn.mongodb.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;
import org.wyn.mongodb.bean.FriendRelationship;
import org.wyn.mongodb.common.SearchBDProvider;

import com.google.code.morphia.dao.BasicDAO;
/**
 * 好友关系mongodb dao层实现
 * @author wyn
 *
 */
public class FriendRelationshipDao extends BasicDAO<FriendRelationship,ObjectId>{
	public FriendRelationshipDao(){
		super(SearchBDProvider.getInstance());
	}
	/**
	 * 创建一个好友关系
	 * @param user1 
	 * @param user2
	 * @return 1创建成功 0未创建 -1关系已存在
	 */
	public int createRelationship(String user1,String user2){
		if(createQuery().filter("user1", user1).filter("user2", user2).countAll() > 0
		|| createQuery().filter("user1", user2).filter("user2", user1).countAll() > 0){//好友关系已经存在
			return -1;
		}
		FriendRelationship rs = new FriendRelationship();
		rs.setUser1(user1);
		rs.setUser2(user2);
		rs.setCreateTime(System.currentTimeMillis());
		save(rs);
		ensureIndexes();
		return 1;//成功创建
	}
	/**
	 * 查询userName的所有好友关系
	 * @param userName
	 * @return 好友用户名列表
	 */
	public List<String> findRelationshipByUser(String userName){
		List<String> result = new ArrayList<String>();
		//用户关系双向 要查两遍
		for(FriendRelationship frs: createQuery().filter("user1", userName)){
			result.add(frs.getUser2());
		}
		for(FriendRelationship frs: createQuery().filter("user2", userName)){
			result.add(frs.getUser1());
		}
		return result;
	}
}
